//
//  OAuthViewController.swift
//  KKWB
//
//  Created by KSY-iOS on 17/1/10.
//  Copyright © 2017年 KK. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    // MARK:- 属性
    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar()
        
        // 2.加载网页
        loadPage()
    }
}

// MARK:- 设置导航栏
extension OAuthViewController {
    
    fileprivate func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OAuthViewController.fullItemClick))
        title = "登录"
    }
    
    fileprivate func loadPage() {
        // 1.获取登录页面的URLString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        // 2.创建对应NSURL
        guard let url = NSURL(string: urlString) else {
            return
        }
        
        // 3.创建NSURLRequest对象
        let request = NSURLRequest(url: url as URL)
        
        // 4.加载request对象
        webView.loadRequest(request as URLRequest)
    }
}

// NARK:- 事件监听
extension OAuthViewController {
    
    @objc fileprivate func closeItemClick() {
    
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func fullItemClick() {
    
        let  jsCode = "document.getElementById('userId').value='18210875071';document.getElementById('passwd').value='ding981397744';"
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
}

// MARK:- webView的delegate方法
extension OAuthViewController : UIWebViewDelegate {
    // webView开始加载网页
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    // webView网页加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // webView加载网页失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 获取accesstoken
        guard let url = request.url else {
            return true
        }
        
        guard url.absoluteString.contains("code=") else {
            return true
        }
        
        let  code: String = url.absoluteString.components(separatedBy: "code=").last!
        
        loadAccessToken(code: code)
        
        return true
    }
    
}

extension OAuthViewController {
    
    fileprivate func loadAccessToken(code: String) {
        
        NetworkTools.shareInstance .loadAccessToken(code: code) { (result: [String : AnyObject]?, error: Error?) in
            
            if error != nil {
                return
            }
            
            guard let accountDict = result else {
                return
            }
            
            let account = UserAccount(dict: accountDict)
            
            self.loadUserInfomation(account: account)
        }
    }
    
    // 获取用户信息
    private func loadUserInfomation(account: UserAccount) {
    
        guard let accessToken = account.access_token else {
            return
        }
        
        guard let uid = account.uid else {
            return
        }
        
        NetworkTools.shareInstance .loadUserInfo(access_token: accessToken, uid: uid) { (result: [String : AnyObject]?, error: Error?) in
            
            if error != nil {
                print(error ?? "")
                return
            }
            
            guard let userInfoDict = result else {
                return
            }
            
            account.screen_name  = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            
            //本地保存
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareInstance.accountPath)
            
            UserAccountViewModel.shareInstance.account = account
            
            // 显示欢迎界面
            self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            })
        }
    }
}





















